#!/usr/bin/env bash


help(){
    cat<<__EOF__
Usage: m user [OPTIONS]

Description: Manage users on MacOS.

Options:
  --help              Show this help message
  --list              List all users
  --info USERNAME     Display information about a user
  --delete USERNAME   Delete a user
  --create            Create a new user, it will ask you for the following information:
                        Username:
                        Full name:
                        Shell [/bin/bash]:
                        Password:
__EOF__
}

confirm(){
    read -r -p "${1} [y/N]: " response
    case ${response,,} in
        [yY]|[yYeEsS])
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}


user_exists(){
    dscl . -list /Users | grep -i "${1}" &>/dev/null
}

user_list(){
    dscl . -list /Users uid
}

user_info(){
    if [ -z "$1" ]; then
        help && exit 1
    fi
    dscl . -read "/Users/${1}" 2>/dev/null || {
        echo "User '${1}' not found" >&2
        exit 1
    }
}

remove_user_from_group(){
    if [ -z "$1" ] || [ -z "$2" ]; then
        help && exit 1
    fi
    sudo dscl . -delete "/Groups/${2}" GroupMembership "${1}"
}

groups_user_belongs(){
    if [ -z "$1" ]; then
        help && exit 1
    fi
    sudo dscl . -list /groups GroupMembership | grep -i "${1}" | awk '{print $1}'
}

user_create(){
    #SECONDARY_GROUPS=""  # for a non-admin user
    #SECONDARY_GROUPS="admin _lpadmin _appserveradm _appserverusr" # for an admin user

    local last_id=$(dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -1)
    last_id=$(expr $last_id + 1)

    local _username _fullname _usershell _password

    read -r -p "Username: " _username
    read -r -p "Full name: " _fullname
    read -r -p "Shell [/bin/bash]: " _usershell
    _usershell=${_usershell:-/bin/bash}
    read -s -r -p "Password: " _password

    [ -z "${_username}" ] && echo "Username is required" >&2 && exit 1
    [ -z "${_fullname}" ] && echo "Full name is required" >&2 && exit 1
    [ -z "${_password}" ] && echo "Password is required" >&2 && exit 1

    printf "\nCreating user '${_username}' (UID: ${last_id})\n"
    sudo dscl . -create /Users/${_username}
    sudo dscl . -create /Users/${_username} UserShell ${_usershell}
    sudo dscl . -create /Users/${_username} RealName "${_fullname}"
    sudo dscl . -create /Users/${_username} UniqueID "${last_id}"
    # staff group by default
    sudo dscl . -create /Users/${_username} PrimaryGroupID 20
    sudo dscl . -create /Users/${_username} NFSHomeDirectory /Users/${_username}

    # Create the home directory
    echo "Creating home directory for user '${_username}'"
    sudo createhomedir -c -u ${_username} &>/dev/null

    # set password
    sudo dscl . -passwd /Users/${_username} "${_password}" &>/dev/null || {
        printf "\nFailed to set password for user '${_username}' maybe because does not comply with password policy.\n" >&2
        printf "Please set the password manually using 'System Preferences > Users & Groups'\n" >&2
        exit 1
    }

}


user_delete(){
    [ -z "$1" ] && help && exit

    if ! user_exists "$1"; then
        echo "User '${1}' not found"
        exit 1
    fi

    if ! confirm "User '${1}' is going to be deleted, are you sure?"; then
        exit 0
    fi

    sudo dscl . -delete "/Users/${1}"
    sudo rm -rf /Users/${1} 2>/dev/null

    for group in $(groups_user_belongs $1); do
        remove_user_from_group $1 $group
    done
}


option="${1}"
shift
case ${option} in
    --help)
        help
        ;;
    --list)
        user_list
        ;;
    --info)
        user_info $@
        ;;
    --create)
        user_create
        ;;
    --delete)
        user_delete $@
        ;;
    *)
        help && exit 1
        ;;
esac
